package com.cqndt.disaster.device.common.service.impl;

import com.cqndt.disaster.device.datasources.MyJdbcTemplate;
import com.cqndt.disaster.device.common.service.SearchService;
import com.cqndt.disaster.device.vo.Column;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private MyJdbcTemplate myJdbcTemplate;

    private final static String PATH = "translate";

    private  static Map<Integer,String> types = null;

    private static Map properties;


    @Override
    public List<Column> getColumns(String tableName) {

        String sql = "SELECT DISTINCT DATA_TYPE, TABLE_NAME,COLUMN_NAME,IS_NULLABLE,COLUMN_COMMENT FROM INFORMATION_SCHEMA.Columns WHERE table_name=? AND COLUMN_NAME IN(\"dis_no\",\"name\",\"area_code\",\"address\",\"dis_type\",\"longitude\",\"latitude\",\"elevation\",\"danger_level\",\"disaster_level\",\"stability\",\"scale\",\"happen_time\",\"threaten_people\",\"threaten_assets\",\"dead_people\",\"direct_loss\",\"remark\",\"threaten_household\",\"threaten_area\",\"threaten_other\",\"back_elevation\",\"area\",\"volume\") GROUP BY COLUMN_NAME";
        List<Column> list = myJdbcTemplate.getJdbcOperations().query(sql,new RowMapper<Column>(){

            @Override
            public Column mapRow(ResultSet rs, int rowNum) throws SQLException {

                Column column = new Column();
                column.setType(rs.getString("data_type"));
                column.setTableName(rs.getString("table_name"));
                column.setName(rs.getString("column_name"));
                column.setNullable(rs.getBoolean("is_nullable"));
                //处理注释里面的括号
                String comment = rs.getString("column_comment");
                int b ;
                if((b = comment.indexOf("("))!=-1||((b = comment.indexOf("（"))!=-1)){
                    comment = comment.substring(0,b);
                }
                column.setLabel(comment);
                String key = column.getTableName()+"."+column.getName();
                List<Column.Option> options = getOptions(key);
                if(options!=null){
                    column.setOptions(options);
                }

                return column;
            }
        },tableName);

        return list;
    }

    public static void main(String[] args) {
        SearchServiceImpl searchService = new SearchServiceImpl();
        Map<Integer ,String> map = searchService.getAllFields(Types.class);
        System.out.println(map);
    }


    private List<Column.Option> getOptions(String key){
        if(properties==null){
            properties = PropertyUtil.loadProperties(PATH);
        }
        Object obj = properties.get(key);
        if(obj == null){
            return null;
        }

        String temp = String.valueOf(obj);

        temp= new String(temp.getBytes(Charset.forName("ISO-8859-1")), Charset.forName("UTF-8"));
        //转换编码
        if(temp.indexOf(",")==-1){
            throw new RuntimeException("名为["+temp+"]的配置项错误，','的用法是否有误，请检查translate.properties");
        }

        String options[] = temp.split(",");
        List<Column.Option> optionList = new ArrayList<>();
        for (int i = 0; i < options.length; i++) {
            String option = options[i];
            int index = option.indexOf('.');
            String label,value;
            if(index!=-1){
                value = option.substring(0,index);
                if(index+1>=option.length()){
                    throw new RuntimeException("名为["+temp+"]的配置项错误,'.'的用法是否有误，请检查translate.properties");
                }
                label = option.substring(index+1);


            }else{
                label=value=option;
            }

            Column.Option co = new Column.Option();
            co.setLabel(label);
            co.setValue(value);
            optionList.add(co);
        }

        return optionList;
    }

    /**
     * 获取一个类的所有属性
     *
     * @param clazz
     * @return
     */
    private static Map<String, Field> getAllClassFields(Class clazz) {
        Map<String, Field> resutlMap = new LinkedHashMap<String, Field>();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                resutlMap.put(field.getName(), field);
            }
        }
        return resutlMap;
    }

    /**
     * 获取java.sql.Types 所有属性值对应的属性名，通过反射将属性值作为key,属性名作为value
     * @param clazz
     * @return
     */
    private Map<Integer ,String> getAllFields(Class clazz){
        Map<Integer ,String> resutlMap = new LinkedHashMap<Integer ,String>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                resutlMap.put(field.getInt(field.getName()), field.getName());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return resutlMap;
    }

    /**
     * 通过反射获取java.sql.Types 对应的TYPE
     * @param type
     * @return
     * @see Types
     */
    private String getType(int type){
        if(types==null){
            types = getAllFields(Types.class);
        }
        return types.get(type);
    }


}
